package com.wtwd.device.utils;


import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;

import java.io.*;

/**
 * @Author ldaoliang
 * @Date create in 17:27 2021/8/10
 * @Description 七牛云文件上传工具类
 */
public class QiNiuUploadUtils {


    /**
     * accessKey
     */
    String accesskey = "*";

    /**
     *
     */
    String secretKey = "*";

    /**
     * 空间名
     */
    String bucket = "*";

    /**
     * 免费域名 30天试用
     */
    String domain = "*";

    /**
     * / 七牛的Configuration类， region2方法表示华南地区，在控制台配置
     */
    Configuration config = new Configuration(Region.region2());
    UploadManager uploadManager = new UploadManager(config);


    public String uploadByBytes(byte[] uploadBytes,String fileName){
        try {
            Auth auth = Auth.create(accesskey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(uploadBytes, fileName, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                   return null;
                }
            }
        } catch (Exception ex) {
            return null;
        }
        return "";
    }

    /**
     * 文件下载
     * @param url  七牛云api生成的带token的地址
     * @param filePath  下载到本地的地址
     */
    public void downloadFile(String url,String filePath){
        OkHttpClient client = new OkHttpClient();
        System.out.println(url);
        Request req = new Request.Builder().url(url).build();
        okhttp3.Response resp = null;
        try {
            resp = client.newCall(req).execute();
            System.out.println(resp.isSuccessful());
            if (resp.isSuccessful()) {
                ResponseBody body = resp.body();
                InputStream is = body.byteStream();
                byte[] data = readInputStream(is);
                //判断文件夹是否存在，不存在则创建
                File file = new File(filePath);
                if (!file.exists() && !file.isDirectory()) {
                    file.mkdir();
                }
                File imgFile = new File(filePath + "1.png");
                FileOutputStream fops = new FileOutputStream(imgFile);
                fops.write(data);
                fops.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Unexpected code " + resp);
        }

    }

    /**
     * 从七牛平台读取的文件输入流转为byte数组。（后面把byte数组输出到文件即可完成下载）
     * @param is
     * @return
     */
    private byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        byte[] buff = new byte[1024 * 2];
        int len = 0;
        try {
            while((len = is.read(buff)) != -1) {
                writer.write(buff, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writer.toByteArray();
    }

    /**
     * 获取私有下载地址
     * @param privateUrl
     * @return
     */
    public String getDownLoadUrl(String privateUrl){
        Auth auth = Auth.create(accesskey,secretKey);
        String s = auth.privateDownloadUrl(privateUrl);
        return s;
    }

    public static void main(String[] args) throws IOException {
        // 文件上传
//        File file = new File("C:\\Users\\Administrator\\Desktop","1.png");
//        FileInputStream fis = new FileInputStream(file);
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        int len;
//        byte[] buffer = new byte[1024];
//        while ((len = fis.read(buffer)) != -1) {
//            baos.write(buffer, 0, len);
//        }
//
//        byte[] data = baos.toByteArray();
//        fis.close();
//        baos.close();
//        new QiNiuUploadUtils().uploadByBytes(data,"1.png");
        // 文件下载
        QiNiuUploadUtils qiniu = new QiNiuUploadUtils();
        // 下载文件（域名 + 文件名；不需要加上空间名，）
        qiniu.downloadFile(qiniu.getDownLoadUrl("*"),"F://");
    }


}
